﻿using CustomModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace Utility
{
    /// <summary>
    /// 用户登陆方式
    /// </summary>
    public enum LoginType
    {
        phone, username, email
    }

    


    /// <summary>
    /// 数据请求结果状态，失败一般用在trycatch中
    /// </summary>
    public enum ErrorLevel
    {
        成功,
        失败

            ,

    }

    /// <summary>
    /// ip模式，内网，外网
    /// </summary>
    public enum IpType
    {
        inner, outer
    }

    /// <summary>
    /// json 和模型相互转化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class Model_JsonConverter<T> where T : class
    {
        /// <summary>
        /// 模型转化为json
        /// </summary>
        /// <param name="model">需要被转化的模型</param>
        /// <returns>返回被转化后的json字符串</returns>
        public static string ModelToJson(T model)
        {

         string res=  JsonConvert.SerializeObject(model, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii, DateFormatString = "yyyy-MM-dd HH:mm:ss" });

            return res;

        }   

        /// <summary>
        /// json转化为模型
        /// </summary>
        /// <param name="content">需要被转化为模型的json字符串</param>
        /// <returns>返回指定的转化后的模型对象</returns>
        public static T JsonToModel(string content)
        {
            try
            {
                T res = JsonConvert.DeserializeObject<T>(content, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii });
                return res;
            }
            catch (Exception)
            {

                throw;
            }
       
        }
    }


    public static class CommonHelper
    {

        

        /// <summary>
        /// 根据分页获得的总条数和每页条数计算出要分多少页
        /// </summary>
        /// <param name="pagesize">每页条数</param>
        /// <param name="pagecount">总条数</param>
        /// <returns></returns>
        public static int ParsePageCount(int pagesize,int pagecount)
        {
            return (pagecount - pagesize - 1) / pagesize;
        }

        private static string CmdPath = @"C:\Windows\System32\cmd.exe";

        /// <summary>
        /// 执行cmd命令
        /// 多命令请使用批处理命令连接符：
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&：当&&前的命令成功时,才执行&&后的命令
        /// ||：当||前的命令失败时,才执行||后的命令]]>
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="output"></param>
        public static void ClipVideoImg(int videoWidth, int videoHeight, string videoPath, string picPath)
        {
            string command = string.Format(  $"D:\\Project\\vs_prj\\HeyPiPi\\Content\\ffmpeg\\ffmpeg.exe -i \"{videoPath}\" -ss {8} -vframes 1 -r 1 -ac 1 -ab 2 -s {videoWidth}*{videoHeight} -f image2 \"{picPath}\"");
            command = command.Trim().TrimEnd('&') + "&exit";//说明：不管命令是否成功均执行exit命令，否则当调用ReadToEnd()方法时，会处于假死状态
            using (Process p = new Process())
            {
                p.StartInfo.FileName = CmdPath;
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(command);
                p.StandardInput.AutoFlush = true;

                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
    /// <summary>
    /// 讲base64 转化未bitmapimage
    /// </summary>
    /// <param name="base64"></param>
    /// <returns></returns>
        public static BitmapImage ConvertBase64ToBitMapImage(string base64)
        {
            base64 = base64.Split(new char[] { ','})[1];
            byte[] data = Convert.FromBase64String(base64);
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(data);
            bi.EndInit();
            return bi;
        }

    /// <summary>
    /// 图片文件转base64
    /// </summary>
    /// <param name="Imagefilename">图片文件</param>
    /// <returns>返回字符串，否则返回空</returns>
    public static string ImgToBase64String(string Imagefilename)
        {

            string _base64String = null;

            using (System.Drawing.Image _image = System.Drawing.Image.FromFile(Imagefilename))
            {
                using (MemoryStream _mStream = new MemoryStream())
                {
                    _image.Save(_mStream, _image.RawFormat);
                    byte[] _imageBytes = _mStream.ToArray();
                    _base64String = Convert.ToBase64String(_imageBytes);

                    return "data:image/jpg;base64," + _base64String;
                }
            }
        }

        /// <summary>
        /// 桌面端token
        /// </summary>
        public static string DeskToken { get; set; }

 

        public static List<CommentModel> GetTree(int parentID, List<CommentModel> comments)
        {
            List<CommentModel> _mainNodes = comments.Where(x => x.ParentId == parentID).ToList();
            List<CommentModel> _otherNodes = comments.Where(x => x.ParentId != parentID).ToList();
            foreach (var item in _mainNodes)
            {
                item.Nodes = GetTree(item.Id, _otherNodes);
            }
            return _mainNodes;
        }

        /// <summary>
        /// 登陆id字符串
        /// </summary>
        public static string userid { get; } = "userid";

        /// <summary>
        /// 用户级别
        /// </summary>
        public static string userlevel { get; } = "userlevel";

        /// <summary>
        /// 手机正则表达式
        /// </summary>
        public static string Phone_Reg { get; } = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

        /// <summary>
        /// 邮箱正则表达式
        /// </summary>
        public static string Email_Reg { get; } = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        /// <summary>
        /// 身份证正则表达式
        /// </summary>
        public static string Identity_Reg { get; } = @"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)";


        /// <summary>
        /// 根据输入判断登陆方式
        /// </summary>
        /// <param name="loginInfo">登陆的数据</param>
        /// <returns>返回登陆方式</returns>
        public static LoginType ValidateLoginType(string loginInfo)
        {
            //验证是否是手机
            Regex phone_regex = new Regex(Phone_Reg);
            Regex email_regex = new Regex(Email_Reg);
            if (phone_regex.IsMatch(loginInfo))
            {
                return LoginType.phone;
            }
            else if (email_regex.IsMatch(loginInfo))
            {
                return LoginType.email;
            }
            else
            {
                return LoginType.username;
            }
        }
        /// <summary>
        /// bitmapimage转base64，可用于html
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static string ConvertBitMapImageToBase64(BitmapImage image)
        {
            byte[] bytearray = null;
          
                Stream smarket = image.StreamSource; ;
            
                    //设置当前位置
                    smarket.Position = 0;
                    using (BinaryReader br = new BinaryReader(smarket))
                    {
                        bytearray = br.ReadBytes((int)smarket.Length);
                    }
            return "data:image/jpg;base64," + Convert.ToBase64String(bytearray);
                
            

        }

        public static byte[] DrowValidateCode(int height, int width, int length, out string code)
        {
            byte[] data = null;
            //随机获取5位验证码
            string Code = MyRandom(length);
            code = Code;
            //创建画板，画板大小70*30，这个可以修改
            Bitmap MyBt = new Bitmap(width, height);
            //创建画笔
            Graphics gp = Graphics.FromImage(MyBt);
            //填充画板为白色，2和-2会让验证码的图片出现边框
            gp.FillRectangle(Brushes.White, 2, 2, MyBt.Width - 4, MyBt.Height - 4);
            //绘制验证码
            gp.DrawString(Code, new Font("宋体", 14), Brushes.Black, new PointF(5, 5));
            //绘制噪线
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                gp.DrawLine(new Pen(RandColor()), rand.Next(MyBt.Width), rand.Next(MyBt.Height), rand.Next(MyBt.Width), rand.Next(MyBt.Height));
            }
            //绘制噪点
            for (int i = 0; i < 5; i++)
            {
                MyBt.SetPixel(rand.Next(MyBt.Width), rand.Next(MyBt.Height), RandColor());

            }
            //释放资源
            gp.Dispose();
            //保存图片
            MemoryStream ms = new MemoryStream();
            MyBt.Save(ms, ImageFormat.Jpeg);
            return ms.GetBuffer();

        }

        //产生len个验证码
        public static string MyRandom(int len)
        {
            //这里是验证码出现的字符，可以更改，可以为中文。中文得修改画板的大小
            String words = "1234567890qwertyuopasdfghjklxcvbnm";
            StringBuilder sb = new StringBuilder();
            Random rand = new Random();
            for (int i = 0; i < len; i++)
            {
                int index = rand.Next(0, words.Length);
                char ch = words[index];
                sb.Append(words[index] + "");
            }
            return sb.ToString();
        }
        //随机产生颜色，为噪点和噪线。
        public static Color RandColor()
        {
            Random rand = new Random();
            int red = rand.Next(10, 200);
            int green = rand.Next(10, 200);
            int blue = rand.Next(10, 200);
            return Color.FromArgb(red, green, blue);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="pwd">需要被加密的密码</param>
        /// <returns>加密后的密文</returns>
        public static string Encryption(string pwd)
        {
            if (string.IsNullOrEmpty(pwd))
            {
                return null;
            }
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pwd));
            StringBuilder sb = new StringBuilder();
            foreach (var item in bytes)
            {
                sb.Append(item.ToString("X").PadLeft(2, '0'));
            }
            return sb.ToString();

        }

        /// <summary>
        /// 正则验证
        /// </summary>
        /// <param name="input">需要被验证的文字</param>
        /// <param name="param">验证规则</param>
        /// <returns></returns>
        public static bool ValidateRegex(string input,string param)
        {
            Regex reg = new Regex(param);
            Match m = reg.Match(input);
            if (m.Success)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获得外网登陆ip
        /// </summary>
        /// <returns></returns>
        public static string GetIp(IpType ipType = IpType.inner)
        {
            if (ipType == IpType.inner)
            {
                IPAddress ipAddr = Dns.Resolve(Dns.GetHostName()).AddressList[0];//获得当前IP地址
                return ipAddr.ToString();
            }

            string ip;
            using (WebClient webClient = new WebClient())
            {
                var content = webClient.DownloadString("http://www.ip138.com/ips1388.asp"); //站获得IP的网页
                //判断IP是否合法
                ip = new Regex(@"\[((\d{1,3}\.){3}\d{1,3})\]").Match(content).Groups[1].Value;
            }
            return ip;
        }

        /// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// post/get提交调用抓取
        /// </summary>
        /// <param name="url">提交地址</param>
        /// <param name="sParam">参数</param>
        /// <returns></returns>
        public static string WebRequestPostOrGet(string url, string sParam)
        {
            byte[] bt = Encoding.UTF8.GetBytes(sParam);
            Uri _url = new Uri(url);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_url);
            req.Method = "Post";
            req.Timeout = 12000;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bt.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bt, 0, bt.Length);
                reqStream.Flush();
            }
            try
            {
                using (WebResponse res = req.GetResponse())
                {
                    Stream resStream = res.GetResponseStream();
                    StreamReader resStreamReader = new StreamReader(resStream, Encoding.UTF8);
                    string resLine;
                    StringBuilder resStringBuilder = new StringBuilder();
                    while ((resLine = resStreamReader.ReadLine()) != null)
                    {
                        resStringBuilder.Append(resLine + Environment.NewLine);
                    }
                    resStream.Close();
                    resStreamReader.Close();
                    return resStringBuilder.ToString();
                }

            }
            catch (Exception e)
            {

                return e.Message;
            }
        }

        /// <summary>
        /// post请求,携带参数
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="content">请求json参数</param>
        /// <param name="auth">是否需要身份验证，true需要，false不需要</param>
        /// <returns></returns>
        public static string HttpPost(string url,Dictionary<string,object> content,bool auth=true)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/x-www-form-urlencoded";
            if (auth)
            {
                string token = "bearer " + DeskToken;
                request.Headers.Add("Authorization", token);
            }

            string postDataStr = "";
            if (!(content == null || content.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in content.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, content[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, content[key]);
                        i++;
                    }
                }

                postDataStr = buffer.ToString();
            }

            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// post请求,不携带参数
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="content">请求json参数</param>
        /// <param name="auth">是否需要身份验证，true需要，false不需要</param>
        /// <returns></returns>
        public static string HttpPost(string url, bool auth = true)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/x-www-form-urlencoded";
            if (auth)
            {
                string token = "bearer " + DeskToken;
                request.Headers.Add("Authorization", token);
            }
            byte[] buffer = encoding.GetBytes("");
            request.ContentLength =0;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }


        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponse(string url)
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = httpClient.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
            return null;
        }


    }
}
